package com.example.birdfriends.utils.mail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Random;
import java.util.Timer;

@Service
public class MailService {
    @Autowired
    private JavaMailSender mailSender = null;

    @Value("${spring.mail.username}")
    private String from;

    public boolean sendMineMail(String email, HttpSession session){
        try{
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("鸟友验证码");  // 邮箱主题
            // 生成随机数验证码
            String code = randomCode();

            // 将随机数放到session
            session.setAttribute("email", email);
            session.setAttribute("code", code);

            mailMessage.setText("【鸟友论坛】邮箱验证码"+code+"，用于邮箱注册论坛账号或修改密码，10分钟内有效。\n验证码提供给他人可能导致账号被盗，请勿泄露，谨防被骗。");
            mailMessage.setTo(email);
            mailMessage.setFrom(from);
            mailSender.send(mailMessage);
            long start = System.currentTimeMillis();
            session.setAttribute("startTime", start);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    // 生成验证码
    public String randomCode(){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for(int i = 0; i < 6; i++){
            str.append(random.nextInt(10));
        }
        return str.toString();
    }
}
